/***********************************************************************
Compile       : gcc -O3 -o extract2 extract2.c
Usage         : ./extract2 N L M processfile solutionfile seed
                (./extract2 10 11 100 Budding.txt Budding-S.txt $RANDOM)
N             : number of the nodes
L             : number of the steps        
M             : number of solutions will be sampled

This program will sample M solutions and write the inputfile for program extended
***********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct solution {
	int num;
	char *edge;
};

void print_help ()
{
	printf ("Usage         : ./extract2 N L M processfile solutionfile randomseed\n");
	printf ("                (./extract2 10 11 100 Budding.txt Budding-S.txt $RANDOM)\n");
	printf ("N             : number of the nodes\n");
	printf ("L             : number of the steps\n");
	printf ("M             : number of solutions will be sampled\n\n");
	printf ("This program will sample M solutions and write the inputfile for program extended\n");
}

void sampling(int N, int L, int pathway[L][N], struct solution solution[N], int select[N], int level)
{
	int i, j;
	static int counter = 0;

	if (level == N)
	{
		char filename[20];
		FILE *fp;

		sprintf (filename, "input-%05d", counter);
		fp = fopen (filename, "w");

		fprintf (fp, "%d\n", N);
		for (j = 0; j < N; j++)
		{
			fprintf (fp, "%d ", pathway[0][j]);
		}
		fprintf (fp, "\n");
		for (i = 0; i < N; i++)
		{
			fprintf (fp, "%s\n", solution[i].edge + 2 * N * select[i]);
		}

		fclose (fp);
		counter ++;

		printf ("%s", filename);
		for (i = 0; i < N; i++)
		{
			printf (" %d", select[i]);
		}
		printf ("\n");
	}
	else
	{
		select[level] = drand48 () * solution[level].num;
		sampling (N, L, pathway, solution, select, level + 1);
	}
}

int main (int argc, char *argv[])
{
	int i, j, N, L, M;
	long int seed;

	if (argc == 1)
	{
		print_help ();
		exit (0);
	}

	N = atoi (argv[1]);
	L = atoi (argv[2]);
	M = atoi (argv[3]);
	seed = atoi (argv[6]);
	srand48 (seed);

	int pathway[L][N];

	FILE *fp;
	char buf[256];

	fp = fopen (argv[4], "r");
	while (fgets (buf, 256, fp))
	{
		for (i = 0; i < L; i++)
		{
			for (j = 0; j < N; j++)
			{
				fscanf (fp, "%d", &pathway[i][j]);
			}
			fgets (buf, 256, fp);
		}
	}
	fclose (fp);

	struct solution solution[N];

	fp = fopen (argv[5], "r");
	for (i = 0; i < N; i++)
	{
		fscanf (fp, "%d", &solution[i].num);
		solution[i].edge = calloc (solution[i].num, 2 * N);
		fgets (buf, 256, fp);
		for (j = 0; j < solution[i].num; j++)
		{
			fgets (buf, 256, fp);
			strncpy (solution[i].edge + 2 * N * j, buf + 10, 2 * N - 1);
			solution[i].edge[2 * N * (j + 1) - 1] = '\0';
		}
	}
	fclose (fp);

	int select[N];

	for (i = 0; i < M; i++)
	{
		sampling (N, L, pathway, solution, select, 0);
	}
}
